
export default class NetClient {

    private ws: WebSocket = null!;
    private address: string = null!;
    public currentObject: any = null!;
    public onConnect: Function = null!;
    public onRecv: Function = null!;
    public onDisconnect: Function = null!;
    public onError: Function = null!;
    public stateConnect = false;

    public connect() {
        this.ws = new WebSocket(this.address);
        this.ws.onopen = () => {
            this.stateConnect = true;
            if (this.onConnect) {
                this.onConnect();
            }
        };

        this.ws.onmessage = (event) => {

            if (this.currentObject && this.currentObject['onNetworkRecv']) {
                let data = JSON.parse(event.data);
                if ('pack' in data && 'action' in data.pack) {
                    this.currentObject['onNetworkRecv'](data.pack.status, data.pack.action, data.pack.data);
                } else {
                    this.currentObject['onNetworkRecv'](false);
                }

            } else if (this.onRecv) {
                this.onRecv(JSON.parse(event.data));
            }

        };


        this.ws.onclose = () => {
            this.stateConnect = false;
            if (this.onDisconnect) {
                this.onDisconnect();
            }
            setTimeout(() => {
                this.connect();
            }, 1000);
        };

        this.ws.onerror = (error) => {
            if (this.onError) {
                this.onError(error);
            }
        };
    }

    public send(message: string) {
        if (this.stateConnect == false) return;
        this.ws.send(message);
    }

    public sendAction(modular: string, action: string, data: any = null) {
        let pack = {
            modular: modular,
            pack: {
                action: action,
                data: data
            }
        }
        this.send(JSON.stringify(pack));
    }


    constructor(address: string) {
        this.address = address;
        this.connect();
    }
}